package tcp

import (
	"context"

	"github.com/panjf2000/gnet/v2"
	"go-micro.dev/v4/server"
	"signal/collector/logger"
)

func NewServer(opts ...server.Option) server.Server {
	opt := server.Options{}
	for _, fn := range opts {
		fn(&opt)
	}
	return &Server{opts: opt}
}

type Server struct {
	opts    server.Options
	handler gnet.EventHandler
}

func (e *Server) Init(option ...server.Option) error {
	for _, opt := range option {
		opt(&e.opts)
	}
	return nil
}

func (e *Server) RegisterHandler(h gnet.EventHandler) {
	e.handler = h
}

func (e *Server) Options() server.Options {
	return e.opts
}

func (e *Server) Handle(handler server.Handler) error {
	return nil
}

func (e *Server) NewHandler(i interface{}, option ...server.HandlerOption) server.Handler {
	return nil
}

func (e *Server) NewSubscriber(s string, i interface{}, option ...server.SubscriberOption) server.Subscriber {
	return nil
}

func (e *Server) Subscribe(subscriber server.Subscriber) error {
	return nil
}

func (e *Server) Start() error {
	go func() {
		logger.Infof("TCP server listen on %s", e.opts.Address)
		if err := gnet.Run(e.handler, e.opts.Address, gnet.WithLogger(logger.DefaultLogger)); err != nil {
			panic(err)
		}
	}()
	return nil
}

func (e *Server) Stop() error {
	return gnet.Stop(context.Background(), e.opts.Address)
}

func (e *Server) String() string {
	return "TCPServer"
}
